import { createRouter, createWebHistory,RouteRecordRaw } from 'vue-router'
import { useMenuStore } from '../store/menu'
import { getMenuList } from '../api/menu/http'
const routes: Array<RouteRecordRaw> =[
        {
            path: '/',
            name: 'layout',
            component: () => import('../components/layout/index.vue'),
            children: [
            ]
        },
        {
            path: '/login',
            name: 'login',
            component: () => import('../views/login/index.vue')
        },
        {
            path: '/test',
            name: 'test',
            component: () => import('../views/test/index.vue')
        }
]

const router = createRouter({
  history: createWebHistory(),
  routes: routes
})
// 路由懒加载
const modules = import.meta.glob('../views/**/*.vue')


// 前置拦截器
router.beforeEach(async (to, from, next) => {
   
    console.log("to:",to)

    if(to.path == '/login'){
      next()
        return
    }
    const menus =  useMenuStore().getMenus;
    if(menus.length > 0){
      next()
    }else {
      try {
      let res: any = await getMenuList()
        console.log("res.data:",res)
       //    判断菜单是否为空
          if(res.code == 400){
             // 跳转登录页
              next('/login')
              return
          }
       await useMenuStore().setMenus(res.data)
       await setMenu(router)

       next({ path: to.path })
      }catch (error) {
         console.log(error)
      }
    }
})

const setMenu  = function setMenu(router: any) {
    const menuStore = useMenuStore()
    // if(menuStore.getMenus.length > 0){
      const menus:any[] =  menuStore.getMenus
      menus.forEach(item => {
            if(item.children && item.children.length > 0){
                    item.children.forEach((child : any) => {
                        if(child.component != 'Layout')
                        router.addRoute('layout',{
                            path: child.path,
                            name: child.name,
                            component:  modules[`../views${child.component}.vue`]
                        })
                    })
            }   
        })
    // }
}

export default router